package com.cn.web.handler;

import cn.com.allunion.common.AllUnionResult;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.Set;

/**
 * 内部异常处理handler
 * Created by YangJie on 2016/4/20.
 */
@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
    /**
     * 处理接口不支持访问方式，抛出的异常
     */
    @Override
    protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        pageNotFoundLogger.warn(ex.getMessage());

        Set<HttpMethod> supportedMethods = ex.getSupportedHttpMethods();
        StringBuilder supportMethodsBuilder = new StringBuilder() ;
        if (!supportedMethods.isEmpty()) {
            headers.setAllow(supportedMethods);
            supportMethodsBuilder.append(supportedMethods) ;
        }

        AllUnionResult result = AllUnionResult.build(status.value(), "该接口只支持" + supportMethodsBuilder.toString()+"方式访问");

        return new ResponseEntity<Object>(result, headers, status);
    }

    /**
     * 处理访问接口，由于没有携带指定的参数，抛出的异常
     */
    @Override
    protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        AllUnionResult result = AllUnionResult.build(status.value(), "参数错误");
        return new ResponseEntity<Object>(result, headers, status);
    }
}
